{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "36609bcf",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Recurrent Neural Networks\n",
    ":label:`sec_rnn`\n",
    "\n",
    "\n",
    "In :numref:`sec_language-model` we described Markov models and $n$-grams for language modeling, where the conditional probability of token $x_t$ at time step $t$ only depends on the $n-1$ previous tokens.\n",
    "If we want to incorporate the possible effect of tokens earlier than time step $t-(n-1)$ on $x_t$,\n",
    "we need to increase $n$.\n",
    "However, the number of model parameters would also increase exponentially with it, as we need to store $|\\mathcal{V}|^n$ numbers for a vocabulary set $\\mathcal{V}$.\n",
    "Hence, rather than modeling $P(x_t \\mid x_{t-1}, \\ldots, x_{t-n+1})$ it is preferable to use a latent variable model,\n",
    "\n",
    "$$P(x_t \\mid x_{t-1}, \\ldots, x_1) \\approx P(x_t \\mid h_{t-1}),$$\n",
    "\n",
    "where $h_{t-1}$ is a *hidden state*  that stores the sequence information up to time step $t-1$.\n",
    "In general,\n",
    "the hidden state at any time step $t$ could be computed based on both the current input $x_{t}$ and the previous hidden state $h_{t-1}$:\n",
    "\n",
    "$$h_t = f(x_{t}, h_{t-1}).$$\n",
    ":eqlabel:`eq_ht_xt`\n",
    "\n",
    "For a sufficiently powerful function $f$ in :eqref:`eq_ht_xt`, the latent variable model is not an approximation. After all, $h_t$ may simply store all the data it has observed so far.\n",
    "However, it could potentially make both computation and storage expensive.\n",
    "\n",
    "Recall that we have discussed hidden layers with hidden units in :numref:`chap_perceptrons`.\n",
    "It is noteworthy that\n",
    "hidden layers and hidden states refer to two very different concepts.\n",
    "Hidden layers are, as explained, layers that are hidden from view on the path from input to output.\n",
    "Hidden states are technically speaking *inputs* to whatever we do at a given step,\n",
    "and they can only be computed by looking at data at previous time steps.\n",
    "\n",
    "*Recurrent neural networks* (RNNs) are neural networks with hidden states. Before introducing the RNN model, we first revisit the MLP model introduced in :numref:`sec_mlp`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "deee527d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:27:13.858746Z",
     "iopub.status.busy": "2023-08-18T19:27:13.858238Z",
     "iopub.status.idle": "2023-08-18T19:27:16.785485Z",
     "shell.execute_reply": "2023-08-18T19:27:16.784592Z"
    },
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cbba908",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## Neural Networks without Hidden States\n",
    "\n",
    "Let's take a look at an MLP with a single hidden layer.\n",
    "Let the hidden layer's activation function be $\\phi$.\n",
    "Given a minibatch of examples $\\mathbf{X} \\in \\mathbb{R}^{n \\times d}$ with batch size $n$ and $d$ inputs, the hidden layer output $\\mathbf{H} \\in \\mathbb{R}^{n \\times h}$ is calculated as\n",
    "\n",
    "$$\\mathbf{H} = \\phi(\\mathbf{X} \\mathbf{W}_{\\textrm{xh}} + \\mathbf{b}_\\textrm{h}).$$\n",
    ":eqlabel:`rnn_h_without_state`\n",
    "\n",
    "In :eqref:`rnn_h_without_state`, we have the weight parameter $\\mathbf{W}_{\\textrm{xh}} \\in \\mathbb{R}^{d \\times h}$, the bias parameter $\\mathbf{b}_\\textrm{h} \\in \\mathbb{R}^{1 \\times h}$, and the number of hidden units $h$, for the hidden layer.\n",
    "So armed, we apply broadcasting (see :numref:`subsec_broadcasting`) during the summation.\n",
    "Next, the hidden layer output $\\mathbf{H}$ is used as input of the output layer, which is given by\n",
    "\n",
    "$$\\mathbf{O} = \\mathbf{H} \\mathbf{W}_{\\textrm{hq}} + \\mathbf{b}_\\textrm{q},$$\n",
    "\n",
    "where $\\mathbf{O} \\in \\mathbb{R}^{n \\times q}$ is the output variable, $\\mathbf{W}_{\\textrm{hq}} \\in \\mathbb{R}^{h \\times q}$ is the weight parameter, and $\\mathbf{b}_\\textrm{q} \\in \\mathbb{R}^{1 \\times q}$ is the bias parameter of the output layer.  If it is a classification problem, we can use $\\mathrm{softmax}(\\mathbf{O})$ to compute the probability distribution of the output categories.\n",
    "\n",
    "This is entirely analogous to the regression problem we solved previously in :numref:`sec_sequence`, hence we omit details.\n",
    "Suffice it to say that we can pick feature-label pairs at random and learn the parameters of our network via automatic differentiation and stochastic gradient descent.\n",
    "\n",
    "## Recurrent Neural Networks with Hidden States\n",
    ":label:`subsec_rnn_w_hidden_states`\n",
    "\n",
    "Matters are entirely different when we have hidden states. Let's look at the structure in some more detail.\n",
    "\n",
    "Assume that we have\n",
    "a minibatch of inputs\n",
    "$\\mathbf{X}_t \\in \\mathbb{R}^{n \\times d}$\n",
    "at time step $t$.\n",
    "In other words,\n",
    "for a minibatch of $n$ sequence examples,\n",
    "each row of $\\mathbf{X}_t$ corresponds to one example at time step $t$ from the sequence.\n",
    "Next,\n",
    "denote by $\\mathbf{H}_t  \\in \\mathbb{R}^{n \\times h}$ the hidden layer output of time step $t$.\n",
    "Unlike with MLP, here we save the hidden layer output $\\mathbf{H}_{t-1}$ from the previous time step and introduce a new weight parameter $\\mathbf{W}_{\\textrm{hh}} \\in \\mathbb{R}^{h \\times h}$ to describe how to use the hidden layer output of the previous time step in the current time step. Specifically, the calculation of the hidden layer output of the current time step is determined by the input of the current time step together with the hidden layer output of the previous time step:\n",
    "\n",
    "$$\\mathbf{H}_t = \\phi(\\mathbf{X}_t \\mathbf{W}_{\\textrm{xh}} + \\mathbf{H}_{t-1} \\mathbf{W}_{\\textrm{hh}}  + \\mathbf{b}_\\textrm{h}).$$\n",
    ":eqlabel:`rnn_h_with_state`\n",
    "\n",
    "Compared with :eqref:`rnn_h_without_state`, :eqref:`rnn_h_with_state` adds one more term $\\mathbf{H}_{t-1} \\mathbf{W}_{\\textrm{hh}}$ and thus\n",
    "instantiates :eqref:`eq_ht_xt`.\n",
    "From the relationship between hidden layer outputs $\\mathbf{H}_t$ and $\\mathbf{H}_{t-1}$ of adjacent time steps,\n",
    "we know that these variables captured and retained the sequence's historical information up to their current time step, just like the state or memory of the neural network's current time step. Therefore, such a hidden layer output is called a *hidden state*.\n",
    "Since the hidden state uses the same definition of the previous time step in the current time step, the computation of :eqref:`rnn_h_with_state` is *recurrent*. Hence, as we said, neural networks with hidden states\n",
    "based on recurrent computation are named\n",
    "*recurrent neural networks*.\n",
    "Layers that perform\n",
    "the computation of :eqref:`rnn_h_with_state`\n",
    "in RNNs\n",
    "are called *recurrent layers*.\n",
    "\n",
    "\n",
    "There are many different ways for constructing RNNs.\n",
    "Those with a hidden state defined by :eqref:`rnn_h_with_state` are very common.\n",
    "For time step $t$,\n",
    "the output of the output layer is similar to the computation in the MLP:\n",
    "\n",
    "$$\\mathbf{O}_t = \\mathbf{H}_t \\mathbf{W}_{\\textrm{hq}} + \\mathbf{b}_\\textrm{q}.$$\n",
    "\n",
    "Parameters of the RNN\n",
    "include the weights $\\mathbf{W}_{\\textrm{xh}} \\in \\mathbb{R}^{d \\times h}, \\mathbf{W}_{\\textrm{hh}} \\in \\mathbb{R}^{h \\times h}$,\n",
    "and the bias $\\mathbf{b}_\\textrm{h} \\in \\mathbb{R}^{1 \\times h}$\n",
    "of the hidden layer,\n",
    "together with the weights $\\mathbf{W}_{\\textrm{hq}} \\in \\mathbb{R}^{h \\times q}$\n",
    "and the bias $\\mathbf{b}_\\textrm{q} \\in \\mathbb{R}^{1 \\times q}$\n",
    "of the output layer.\n",
    "It is worth mentioning that\n",
    "even at different time steps,\n",
    "RNNs always use these model parameters.\n",
    "Therefore, the parametrization cost of an RNN\n",
    "does not grow as the number of time steps increases.\n",
    "\n",
    ":numref:`fig_rnn` illustrates the computational logic of an RNN at three adjacent time steps.\n",
    "At any time step $t$,\n",
    "the computation of the hidden state can be treated as:\n",
    "(i) concatenating the input $\\mathbf{X}_t$ at the current time step $t$ and the hidden state $\\mathbf{H}_{t-1}$ at the previous time step $t-1$;\n",
    "(ii) feeding the concatenation result into a fully connected layer with the activation function $\\phi$.\n",
    "The output of such a fully connected layer is the hidden state $\\mathbf{H}_t$ of the current time step $t$.\n",
    "In this case,\n",
    "the model parameters are the concatenation of $\\mathbf{W}_{\\textrm{xh}}$ and $\\mathbf{W}_{\\textrm{hh}}$, and a bias of $\\mathbf{b}_\\textrm{h}$, all from :eqref:`rnn_h_with_state`.\n",
    "The hidden state of the current time step $t$, $\\mathbf{H}_t$, will participate in computing the hidden state $\\mathbf{H}_{t+1}$ of the next time step $t+1$.\n",
    "What is more, $\\mathbf{H}_t$ will also be\n",
    "fed into the fully connected output layer\n",
    "to compute the output\n",
    "$\\mathbf{O}_t$ of the current time step $t$.\n",
    "\n",
    "![An RNN with a hidden state.](../img/rnn.svg)\n",
    ":label:`fig_rnn`\n",
    "\n",
    "We just mentioned that the calculation of $\\mathbf{X}_t \\mathbf{W}_{\\textrm{xh}} + \\mathbf{H}_{t-1} \\mathbf{W}_{\\textrm{hh}}$ for the hidden state is equivalent to\n",
    "matrix multiplication of the\n",
    "concatenation of $\\mathbf{X}_t$ and $\\mathbf{H}_{t-1}$\n",
    "and the\n",
    "concatenation of $\\mathbf{W}_{\\textrm{xh}}$ and $\\mathbf{W}_{\\textrm{hh}}$.\n",
    "Though this can be proven mathematically,\n",
    "in the following we just use a simple code snippet as a demonstration.\n",
    "To begin with,\n",
    "we define matrices `X`, `W_xh`, `H`, and `W_hh`, whose shapes are (3, 1), (1, 4), (3, 4), and (4, 4), respectively.\n",
    "Multiplying `X` by `W_xh`, and `H` by `W_hh`, and then adding these two products,\n",
    "we obtain a matrix of shape (3, 4).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "09b186bf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:27:16.789724Z",
     "iopub.status.busy": "2023-08-18T19:27:16.789025Z",
     "iopub.status.idle": "2023-08-18T19:27:16.822423Z",
     "shell.execute_reply": "2023-08-18T19:27:16.821267Z"
    },
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 1.2526,  0.0580, -3.3460, -0.2519],\n",
       "        [-1.3064,  1.4132, -0.1435,  0.3482],\n",
       "        [ 3.1495,  0.8172,  1.5167, -0.9038]])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X, W_xh = torch.randn(3, 1), torch.randn(1, 4)\n",
    "H, W_hh = torch.randn(3, 4), torch.randn(4, 4)\n",
    "torch.matmul(X, W_xh) + torch.matmul(H, W_hh)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59eb3429",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "Now we concatenate the matrices `X` and `H`\n",
    "along columns (axis 1),\n",
    "and the matrices\n",
    "`W_xh` and `W_hh` along rows (axis 0).\n",
    "These two concatenations\n",
    "result in\n",
    "matrices of shape (3, 5)\n",
    "and of shape (5, 4), respectively.\n",
    "Multiplying these two concatenated matrices,\n",
    "we obtain the same output matrix of shape (3, 4)\n",
    "as above.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "52ac9b29",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:27:16.827070Z",
     "iopub.status.busy": "2023-08-18T19:27:16.826785Z",
     "iopub.status.idle": "2023-08-18T19:27:16.833496Z",
     "shell.execute_reply": "2023-08-18T19:27:16.832705Z"
    },
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 1.2526,  0.0580, -3.3460, -0.2519],\n",
       "        [-1.3064,  1.4132, -0.1435,  0.3482],\n",
       "        [ 3.1495,  0.8172,  1.5167, -0.9038]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.matmul(torch.cat((X, H), 1), torch.cat((W_xh, W_hh), 0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce7632f2",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "## RNN-Based Character-Level Language Models\n",
    "\n",
    "Recall that for language modeling in :numref:`sec_language-model`,\n",
    "we aim to predict the next token based on\n",
    "the current and past tokens;\n",
    "thus we shift the original sequence by one token\n",
    "as the targets (labels).\n",
    ":citet:`Bengio.Ducharme.Vincent.ea.2003` first proposed\n",
    "to use a neural network for language modeling.\n",
    "In the following we illustrate how RNNs can be used to build a language model.\n",
    "Let the minibatch size be one, and the sequence of the text be \"machine\".\n",
    "To simplify training in subsequent sections,\n",
    "we tokenize text into characters rather than words\n",
    "and consider a *character-level language model*.\n",
    ":numref:`fig_rnn_train` demonstrates how to predict the next character based on the current and previous characters via an RNN for character-level language modeling.\n",
    "\n",
    "![A character-level language model based on the RNN. The input and target sequences are \"machin\" and \"achine\", respectively.](../img/rnn-train.svg)\n",
    ":label:`fig_rnn_train`\n",
    "\n",
    "During the training process,\n",
    "we run a softmax operation on the output from the output layer for each time step, and then use the cross-entropy loss to compute the error between the model output and the target.\n",
    "Because of the recurrent computation of the hidden state in the hidden layer, the output, $\\mathbf{O}_3$,  of time step 3 in :numref:`fig_rnn_train` is determined by the text sequence \"m\", \"a\", and \"c\". Since the next character of the sequence in the training data is \"h\", the loss of time step 3 will depend on the probability distribution of the next character generated based on the feature sequence \"m\", \"a\", \"c\" and the target \"h\" of this time step.\n",
    "\n",
    "In practice, each token is represented by a $d$-dimensional vector, and we use a batch size $n>1$. Therefore, the input $\\mathbf X_t$ at time step $t$ will be an $n\\times d$ matrix, which is identical to what we discussed in :numref:`subsec_rnn_w_hidden_states`.\n",
    "\n",
    "In the following sections, we will implement RNNs\n",
    "for character-level language models.\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "A neural network that uses recurrent computation for hidden states is called a recurrent neural network (RNN).\n",
    "The hidden state of an RNN can capture historical information of the sequence up to the current time step. With recurrent computation, the number of RNN model parameters does not grow as the number of time steps increases. As for applications, an RNN can be used to create character-level language models.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. If we use an RNN to predict the next character in a text sequence, what is the required dimension for any output?\n",
    "1. Why can RNNs express the conditional probability of a token at some time step based on all the previous tokens in the text sequence?\n",
    "1. What happens to the gradient if you backpropagate through a long sequence?\n",
    "1. What are some of the problems associated with the language model described in this section?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c7bc477",
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1050)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}